<template>
    <div class="company-constant-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>单位基本信息</span>
                </div>
            </template>

            <el-table :data="constantList" v-loading="loading" style="width: 100%">
                <el-table-column align="center" prop="key" label="字段">
                    <template #default="{ row }">
                        {{ FIELD_CONFIG[row.key]?.label }}
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="value" label="值" />
                <el-table-column align="center" prop="description" label="说明" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ FIELD_CONFIG[row.key]?.description }}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 编辑对话框 -->
        <el-dialog :draggable="true" title="编辑信息" v-model="dialogVisible" width="500px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item :label="FIELD_CONFIG[form.key]?.label" prop="value">
                    <el-input v-model="form.value" :placeholder="`请输入${FIELD_CONFIG[form.key]?.label}`" />
                    <div class="form-description">{{ FIELD_CONFIG[form.key]?.description }}</div>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitting">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import {
    getCompanyConstantApi,
    createCompanyConstantApi,
    updateCompanyConstantApi,
} from '@/api/constant'
import { useCompanyStore } from '@/stores/company'
import { FIELD_CONFIG } from '@/constants'
import { storeToRefs } from 'pinia'

const companyStore = useCompanyStore()
const { currentCompany } = storeToRefs(companyStore)

const loading = ref(false)
const submitting = ref(false)
const constantList = ref([])
const dialogVisible = ref(false)
const formRef = ref(null)

const form = ref({
    id: undefined,
    key: '',
    value: '',
    company_id: undefined
})

const rules = {
    value: [
        { required: true, message: '请输入内容', trigger: 'blur' }
    ]
}

// 初始化固定字段数据
const initializeConstants = (existingData) => {
    const defaultConstants = Object.keys(FIELD_CONFIG).map(key => ({
        key,
        value: '无'
    }))

    return defaultConstants.map(defaultItem => {
        const existingItem = existingData.find(item => item.key === defaultItem.key)
        if (existingItem) {
            return existingItem
        }
        return {
            ...defaultItem,
            company_id: currentCompany.value.id
        }
    })
}

// 获取常量列表
const fetchConstantList = async () => {
    // 如果没有选择，不进行请求
    if (!currentCompany.value?.id) return

    try {
        loading.value = true
        const { data } = await getCompanyConstantApi({
            id: currentCompany.value.id
        })
        constantList.value = initializeConstants(data)
    } catch (error) {
        ElMessage.error('获取信息失败')
    } finally {
        loading.value = false
    }
}

// 打开编辑对话框
const handleEdit = (row) => {
    form.value = {
        ...row,
        company_id: currentCompany.value.id
    }
    dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitting.value = true

        // 如果是默认值"无"，说明需要新建
        const existingItem = constantList.value.find(item =>
            item.key === form.value.key && item.value !== '无' && item.id
        )

        if (existingItem) {
            await updateCompanyConstantApi(form.value)
            ElMessage.success('更新成功')
        } else {
            await createCompanyConstantApi({
                key: form.value.key,
                value: form.value.value,
                company_id: form.value.company_id
            })
            ElMessage.success('添加成功')
        }

        dialogVisible.value = false
        await fetchConstantList()
    } catch (error) {
        ElMessage.error('保存失败')
    } finally {
        submitting.value = false
    }
}

// 监听当前公司变化
watch(
    () => currentCompany.value?.id,
    (newId) => {
        if (newId) {
            fetchConstantList()
        } else {
            // 当没有选择公司时，清空列表
            constantList.value = []
        }
    },
    { immediate: true } // 立即执行一次
)

// 由于使用了 watch 的 immediate 选项，这里可以移除 onMounted
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.form-description {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
    line-height: 1.4;
}
</style>